//
//  NetworkRequestBase.m
//  TicketingSystem
//
//  Created by Conner Wu on 15/7/20.
//  Copyright (c) 2015年 Beyondsoft. All rights reserved.
//

#import "NetworkRequestBase.h"
#import "AppDelegate.h"

@interface NetworkRequestBase ()
{
    HttpMethod _method;
    NSUInteger _retryCount;
    CompletedBlock _completedBlock;
}
@end

@implementation NetworkRequestBase

- (void)dealloc
{
    NSLog(@"%s", __FUNCTION__);
}

- (id)init
{
    self = [self initWithLoadingSuperview:((AppDelegate *)[UIApplication sharedApplication].delegate).window];
//    self = [self initWithLoadingSuperview:[UIApplication sharedApplication].keyWindow];
    return self;
}

- (id)initWithLoadingSuperview:(UIView *)view
{
    self = [super init];
    if (self) {
        _retryCount = 0;
        _showLoading = YES;
        _showError = YES;
        _loadingSuperView = view;
    }
    return self;
}

#pragma mark GET Method

- (void)startGet
{
    [self sendRequest:HttpMethodGet];
}

- (void)startPut
{
    [self sendRequest:HttpMethodPut];
}

- (void)startDelete
{
    [self sendRequest:HttpMethodDelete];
}


#pragma mark POST Method

- (void)startPost
{
    // 保存image
    NSMutableArray *fileArray;
    if (_files && _files.count > 0) {
        fileArray = [NSMutableArray array];
        for (unsigned int i = 0; i < _files.count; i++) {
            NSDictionary *dic = [_files objectAtIndex:i];
            UIImage *image = [self scaleImage:[dic objectForKey:@"profileImage"] toSize:CGSizeMake(800, 600)];
            
            NSData *data;
            if (UIImagePNGRepresentation(image) == nil) {
                data = UIImageJPEGRepresentation(image, 1.0);
            } else {
                data = UIImagePNGRepresentation(image);
            }
            
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
            NSString *cachePath = [paths objectAtIndex:0];
            NSString *filePath = [cachePath stringByAppendingFormat:@"/upload-file-%i.jpg", i];
            
            [UIImageJPEGRepresentation(image, 0.6) writeToFile:filePath atomically:YES];
            
            NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [newDic setObject:filePath forKey:@"path"];
            [fileArray addObject:newDic];
        }
    }
    _files = fileArray;
    
    [self sendRequest:HttpMethodPost];
}

#pragma mark Request Method

- (void)sendRequest:(HttpMethod)type
{
    _retryCount++;
    _method = type;
    
    
    NetworkOperation *networkOperation = [[NetworkOperation alloc] init];
    networkOperation.flag = _flag;
    networkOperation.path = [_path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    networkOperation.params = _params;
    networkOperation.files = _files;
    networkOperation.loadingSuperView = _loadingSuperView;
    networkOperation.showLoading = _showLoading;
    networkOperation.completion = ^(id result) {
        NSDictionary *dicResult = (NSDictionary *)result;
        NSUInteger code = [[dicResult objectForKey:kHttpReturnCodeKey] integerValue];
        BOOL succ = false;
        if (code == kHttpReturnSuccCode)
        {
            succ = YES;
        }
        
        if (!succ)
        {
            if (_retryCount < kHttpRetryCount)
            {
                [self sendRequest:_method];
                return;
            }
        }
        if (_completedBlock)
        {
            if (_isNotDataStr)
            {
                _completedBlock(result,[result objectForKey:kHttpReturnMsgKey],nil,succ);
            }
            else
            {
                _completedBlock([result objectForKey:kHttpReturnResultKey],[result objectForKey:kHttpReturnMsgKey],nil,succ);
            }
            
        }
    };
    
    if (type == HttpMethodGet)
    {
        [networkOperation sendDataByGet];
    }
    else if (type == HttpMethodPut)
    {
        [networkOperation sendDataByPut];
    }
    else if (type == HttpMethodDelete)
    {
        [networkOperation sendDataByDelete];
    }
    else
    {
        [networkOperation sendDataByPost];
    }
}

// private
- (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)size{
    UIImage *newImage;
    
    int h = image.size.height;
    int w = image.size.width;
    
    if(h <= size.height && w <= size.width) {
        newImage = image;
    } else {
        float destWith = 0.0f;
        float destHeight = 0.0f;
        
        float suoFang = (float)w/h;
        float suo = (float)h/w;
        if (w > h) {
            destWith = (float)size.width;
            destHeight = size.width * suo;
        } else {
            destHeight = (float)size.height;
            destWith = size.height * suoFang;
        }
        
        CGSize itemSize = CGSizeMake(destWith, destHeight);
        UIGraphicsBeginImageContext(itemSize);
        CGRect imageRect = CGRectMake(0, 0, destWith, destHeight);
        [image drawInRect:imageRect];
        UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        newImage = newImg;
    }
    return newImage;
}


// 定义回调
- (void)completion:(CompletedBlock)completion
{
    _completedBlock = completion;
}


@end
